import React, { useState } from 'react'
import servicer from '../../api/servicer'
import { Banner, Button, Card, Checkbox, Col, Dropdown, Input, Row, Select, Spin, Toast } from '@douyinfe/semi-ui'
import { IconClear } from "@douyinfe/semi-icons"
import { notificationCatchErr } from '../../lib/utils'

export default function AutoSendComment() {
    const [items, setItems] = useState([])
    const [loading, setLoading] = useState(false);

    React.useEffect(() => {
        setLoading(true)
        servicer.listAutoSendComment().then(({ data }) => {
            setLoading(false)
            setItems(data)
        }).catch(notificationCatchErr("获取失败"))
    }, [])

    const updateItems = (index, item, check = false) => {
        items[index] = item

        if (check) {
            item.editable = true;
            if (!item.name) return Toast.error('名称必须填写')
            if (!item.circularType) return Toast.error('发评顺序必须填写')
            if (!item.intervalSeconds) return Toast.error('发评间隔必须填写')
            if (!item.sleepMins) return Toast.error('休息时长必须填写')
            if (!item.durationMins) return Toast.error('单次发评间隔必须填写')
            for (let i = 0; i < item.comments.length; i++) {
                if (item.comments[i].trim() === '') return Toast.error('评论内容必须填写')
            }
            setLoading(true)
            servicer.setAutoSendComment(item).then(({ data }) => {
                setLoading(false)
                item.id = data.id
                items[index] = item
                item.editable = false;
                setItems([...items])
            })

        } else {
            setItems([...items])
        }
    };

    const deleteItems = (index) => {
        const item = items.splice(index, 1)
        setItems([...items])

        if (item[0].id) {
            setLoading(true)
            servicer.deleteAutoSendComment({ id: item[0].id }).then(() => {
                setLoading(false)
                setItems([...items])
            }).catch(notificationCatchErr("删除失败"))
        }
    }


    return <>
        <Spin spinning={loading}>
            <Banner
                fullMode={false}
                type="info"
                bordered
                title={<div style={{ fontWeight: 600, fontSize: '14px', lineHeight: '20px' }}>自动发屏</div>}
                description={<div> 提前编辑好公屏互动话术，在直播时可自动循环发送一个组内的评论内容，最多创建20组</div>}
                closeIcon={null}
            >
                <Button style={{ float: 'right', position: 'relative', top: '-42px' }}
                    onClick={() => {
                        if (items.length >= 20) {
                            return Toast.error('最多添加20组评论');
                        }

                        for (let i = 0; i < items.length; i++) {
                            if (!items[i].id) return Toast.error('未提交的评论组(序号' + (i + 1) + ')，无法添加新的评论组');
                        }

                        const _items = [...items, {
                            name: '新评论组',
                            circularType: '',
                            autoTop: false,
                            autoTopMins: 0,
                            durationMins: 0,
                            intervalSeconds: 0,
                            sleepMins: 0,
                            comments: [''],
                            editable: true
                        }]

                        setItems(_items)
                    }}
                >新回复组</Button>
            </Banner>


            <div className='grid gap-4 sm:grid-cols-1'>
                {
                    items.map((item, index) => (
                        <Card
                            key={'autoSendComment' + index}
                            style={{ marginTop: '10px', width: '100%' }}
                            title={null}
                            headerLine={false}

                        >
                            <Row>
                                <Col span={16}>
                                    <Input value={item.name}
                                        disabled={!item.editable}
                                        onChange={(value) => {
                                            item.name = value
                                            updateItems(index, item)
                                        }} style={{ display: 'inline-block', width: '160px' }} />
                                </Col>
                                <Col span={8} style={{ textAlign: 'right' }}>
                                    <Dropdown
                                        style={{ float: 'right' }}
                                        render={
                                            <Dropdown.Menu>
                                                {
                                                    item.editable ?
                                                        <Dropdown.Item onClick={
                                                            () => { item.editable = false; updateItems(index, item, true) }
                                                        }>保存</Dropdown.Item> :
                                                        <Dropdown.Item onClick={
                                                            () => { item.editable = true; updateItems(index, item) }
                                                        }>编辑</Dropdown.Item>
                                                }
                                                <Dropdown.Item onClick={() => deleteItems(index)}>删除 </Dropdown.Item>
                                            </Dropdown.Menu>
                                        }
                                    >
                                        <Button>操作</Button>
                                    </Dropdown>
                                </Col>
                            </Row>


                            <div style={{ margin: '10px 0' }}>
                                发评顺序：<span style={{ display: 'inline-block', marginRight: '15px' }}>
                                    <Select
                                        disabled={!item.editable}
                                        value={item.circularType}
                                        placeholder="选择"
                                        onChange={(value) => { item.circularType = value; updateItems(index, item) }}>
                                        <Select.Option value="random">随机</Select.Option>
                                        <Select.Option value="sequence">顺序</Select.Option>
                                    </Select>
                                </span>
                                每条间隔：<Input
                                    disabled={!item.editable}
                                    value={item.intervalSeconds}
                                    onChange={(value) => {
                                        item.intervalSeconds = Number(value)
                                        updateItems(index, item)
                                    }} style={{ display: 'inline-block', width: '50px' }} />秒
                                <div style={{ 'display': 'inline-block', 'width': '10px' }}></div>
                                单次轮评：<Input
                                    disabled={!item.editable}
                                    value={item.durationMins} onChange={(value) => {
                                        item.durationMins = Number(value)
                                        updateItems(index, item)
                                    }} style={{ display: 'inline-block', width: '50px' }} />分钟
                                <div style={{ 'display': 'inline-block', 'width': '10px' }}></div>
                                休息时长：<Input
                                    disabled={!item.editable}
                                    onChange={(value) => {
                                        item.sleepMins = Number(value)
                                        updateItems(index, item)
                                    }} value={item.sleepMins} style={{ display: 'inline-block', width: '50px' }} />分钟
                                <div style={{ 'display': 'inline-block', 'width': '10px' }}></div>
                                评论置顶间隔： <Checkbox
                                    disabled={!item.editable}
                                    checked={!!item.autoTop}
                                    onChange={(e) => {
                                        item.autoTop = !!e.target.checked
                                        updateItems(index, item)
                                    }}
                                    style={{ verticalAlign: 'middle', marginRight: '15px', display: 'inline-block' }} />
                                {
                                    item.autoTop ? <div style={{ 'display': 'inline-block' }}>间隔时长：
                                        <Input
                                            disabled={!item.editable}
                                            onChange={(value) => {
                                                item.autoTopMins = Number(value)
                                                updateItems(index, item)
                                            }} value={item.autoTopMins} style={{ display: 'inline-block', width: '50px' }} />分钟</div> : <></>
                                }
                            </div>

                            {
                                item.comments?.map((comment, _index) => {
                                    return <div
                                        key={'autoSendCommentComment' + Math.random() + index}
                                        className="flex w-full items-center space-x-2 auto-comment-item" style={{ marginTop: '5px' }}>
                                        <Input value={comment} disabled={!item.editable}
                                            onChange={(value) => {
                                                item.comments[_index] = value
                                                updateItems(index, item)
                                            }} />
                                        {
                                            item.editable ? <Button size={'small'}
                                                onClick={() => {
                                                    if (item.comments.length === 1) {
                                                        return Toast.error('至少保留一条评论')
                                                    }

                                                    item.comments.splice(_index, 1)
                                                    updateItems(index, item)
                                                }}
                                            >
                                                <IconClear size='default' style={{ height: '30px', lineHeight: '30px' }} />
                                            </Button> : <></>
                                        }
                                    </div>
                                })
                            }
                        </Card>

                    ))
                }
            </div>
        </Spin>

    </>
}
